In [ ]:
Python
takes care of GC
automatically for you, and as developer you normally do not have to "worry" about it. But, its still good idea to learn about it, so that you can create your program in such a way that it takes benefit of python's GC
.
Previously Python
used to solely rely on reference count
algorithm to allocate and de-allocate memory. Since, Python 1.5.2
it has changed. Now, it has two strategies for memory allocation
Reference counting
works by counting the times an object is referenced by other objects. When any reference to an object is removed, its corresponding reference count
for an object
is decremented
and when it becomes zero
the object
is deallocated
.
RC is extremely efficient in memory management but it has few issues. Few of the issues are listed below.
In [2]:
def cyclic_reference():
if "arry" not in locals():
print("create new")
arry = [ ]
arry.append(arry)
print(arry)
In [3]:
cyclic_reference()
cyclic_reference()
cyclic_reference()
In [13]:
good = ["good"]
b = []
b.append(good)
good.append(b)
print( b)
del(good)
print(b)
The data of good lives even after we deleted it ...
lets take another example, to validate it further
In [26]:
a = ["test"]
b = []
b.append(a)
print(id(a))
print(id(b[0]))
print(b)
del(a)
print(id(b[0]))
print(b)
In [27]:
import gc
print(gc.garbage)
del(b)
gc.collect()
print(gc.garbage)
In [ ]:
In [ ]:
In [ ]:
In [28]:
import gc
print ("Garbage collection thresholds: ", gc.get_threshold())
What the above information means, is that your application can have about 700 objects before any automatic garbage collector will execute.
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: